package me.gavin.base

import android.graphics.Point
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import me.gavin.util.log

abstract class BaseDialog : DialogFragment() {

    abstract val layoutId: Int

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, 0)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(layoutId, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initLayout()
        afterCreate(savedInstanceState)
    }

    protected open fun initLayout() {
        dialog?.window?.run {
            setBackgroundDrawableResource(android.R.color.transparent)
            val point = Point().also { windowManager.defaultDisplay.getSize(it) }
            setLayout((point.x * 0.8f).toInt(), WindowManager.LayoutParams.WRAP_CONTENT)
        }
    }

    abstract fun afterCreate(savedInstanceState: Bundle?)

    fun show(manager: FragmentManager) {
        show(manager, this.javaClass.simpleName.also {
            "show - $it".log()
        })
    }

}

abstract class BindingDialog<B : ViewDataBinding> : BaseDialog() {

    lateinit var binding: B
        private set

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, layoutId, container, false)
        binding.lifecycleOwner = this
        return binding.root
    }

}